package com.leyou.search.service;


import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.*;
import com.leyou.search.FeignClient.CategoryClient;
import com.leyou.search.FeignClient.GoodsClient;
import com.leyou.search.FeignClient.SpecificationClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class IndexService {
    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specificationClient;
    @Autowired
    private GoodsRepository goodsRepository;

    public Goods buildGoods(SpuBo spu) {
        //todo 将spu的值赋给goods对象，有四个属性没有，all,skus,price,specs
        Goods goods = new Goods();

        BeanUtils.copyProperties(spu, goods);

        //获取SPU的ID
        Long id = spu.getId();
        //商品分类名称
        List<String> names = categoryClient.queryNameByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));

        String all = spu.getTitle() + " " + StringUtils.join(names, " ");
        goods.setAll(all);
        //sku集合
        List<Sku> skus = goodsClient.querySkuBySpuId(id);
        //处理sku
        //把商品价格取出单独存放，便于展示
        ArrayList<Long> prices = new ArrayList<>();
        List<Map<String, Object>> skuList = new ArrayList<>();
        for (Sku sku : skus) {
            prices.add(sku.getPrice());
            Map<String, Object> skuMap = new HashMap<>();
            skuMap.put("id", sku.getId());
            skuMap.put("title", sku.getTitle());
            skuMap.put("image", StringUtils.isBlank(sku.getImages()) ? "" : sku.getImages().split(",")[0]);
            skuMap.put("price", sku.getPrice());
            skuList.add(skuMap);
        }
        goods.setPrice(prices);

        goods.setSkus(JsonUtils.serialize(skuList));
        //spuDetail
        SpuDetail spuDetail = goodsClient.querySpuDetailById(id);
        //查询分类对应的规格参数
        List<SpecParam> params = specificationClient.querySpecParam(null, spu.getCid3(), true, null);
        //通过规格参数值
        Map<Long, String> genericMap = JsonUtils.parseMap(spuDetail.getGenericSpec(), Long.class, String.class);
        Map<Long, List<String>> specialMap = JsonUtils.nativeRead(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });
        //处理规格参数现实问题，默认显示id+值，处理后显示id对应的名称+值
        Map<String, Object> specs = new HashMap<>();

        for (SpecParam param : params) {
            String name = param.getName();
            Object value = null;
            if (param.getGeneric()) {
                Long id1 = param.getId();
                value = genericMap.get(id1);
                if (value == null) {
                    value = "其他";
                    continue;
                }
                if (param.getNumeric()) {
                    value = chooseSegment(value.toString(), param);
                }
            } else {
                Long id1 = param.getId();
                value = specialMap.get(id1);
            }
            specs.put(name, value);
        }
        goods.setSpecs(specs);
        return goods;
    }

    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = NumberUtils.toDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }
    public void createIndex(Long id){
        Spu spu = this.goodsClient.querySpuById(id);
        SpuBo spuBo = new SpuBo();
        BeanUtils.copyProperties(spu,spuBo);
        Goods goods = this.buildGoods(spuBo);
        this.goodsRepository.save(goods);
    }

    public void deleteIndex(Long id) {
        this.goodsRepository.deleteById(id);
    }
}
